<?php

namespace platform\controllers\authority;

use platform\controllers\BaseController;
use platform\models\authority\Role;
use yii\web\NotFoundHttpException;

class RoleController extends BaseController
{
    public $modelClass = 'platform\models\authority\Role';

    public function actions()
    {
        $actions = parent::actions();

        // 禁用 "delete" 和 "create" 动作
        unset($actions['index'], $actions['view'], $actions['create'], $actions['update'], $actions['delete']);

        return $actions;
    }

    public function actionIndex()
    {
        return ['items' => array_values(Role::getRoles())];
    }

    public function actionCreate()
    {
        $model = new Role();
        $model->load(\Yii::$app->request->post(), '');
        return $model->create();
    }

    public function actionUpdate($name)
    {
        $model = new Role();
        $model->load(\Yii::$app->request->post(), '');
        return $model->update($name);
    }

    public function actionDelete($name)
    {
        $this->getRole($name);
        $model = new Role();
        return $model->delete($name);
    }

    public function actionAssign($name)
    {
        $this->getRole($name);
        return (new Role())->assign($name);
    }

    public function actionRemove($name)
    {
        $this->getRole($name);
        return (new Role())->remove($name);
    }

    public function actionAssignedPermissions($name)
    {
        $items = Array_values((new Role())->getAssignedPermissions($name));
        sort($items);
        return ['items' => $items];
    }

    /**
     * @param $name
     * @throws NotFoundHttpException
     */
    protected function getRole($name)
    {
        $role = Role::getRole($name);
        if (!$role) {
            throw new NotFoundHttpException('角色不存在');
        }
    }
}